package com.shortlink.server.controller;

import com.shortlink.common.base.Result;
import com.shortlink.common.base.Results;
import com.shortlink.common.exception.ServiceException;
import com.shortlink.server.dto.shortlinkmapper.ShortLinkMapperInsertReqDTO;
import com.shortlink.server.dto.shortlinkmapper.ShortLinkMapperUpdateReqDTO;
import com.shortlink.server.dto.shortlinkmapper.ShortLinkReqDTO;
import com.shortlink.server.service.ShortLinkMapperService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 短链接映射控制层
 *
 * @author wp
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class ShortLinkMapperController {
    private final ShortLinkMapperService shortLinkMapperService;

    @PostMapping("/api/shortlink-mappers")
    Result<Void> insert(@RequestBody ShortLinkMapperInsertReqDTO shortLinkMapperInsert) {
        shortLinkMapperService.signalInsert(shortLinkMapperInsert);
        return Results.success();
    }

    @PostMapping("/api/shortlink-mappers/save/batch")
    Result<Void> batchInsert(@RequestBody List<ShortLinkMapperInsertReqDTO> shortLinkMapperInserts) {
        shortLinkMapperService.batchInsert(shortLinkMapperInserts);
        return Results.success();
    }

    @PutMapping("/api/shortlink-mappers")
    Result<Void> update(@RequestBody ShortLinkMapperUpdateReqDTO shortLinkMapperUpdate) {
        shortLinkMapperService.updateByShortUri(shortLinkMapperUpdate);
        return Results.success();
    }

    @DeleteMapping("/api/shortlink-mappers/{id}")
    Result<Void> moveToRecycleBin(@PathVariable Long id) {
        shortLinkMapperService.moveToRecycleBin(id);
        return Results.success();
    }

    @DeleteMapping("/api/shortlink-mappers/delete/actual/{id}")
    Result<Void> delete(@PathVariable Long id) {
        boolean succeed = shortLinkMapperService.removeById(id);
        if (succeed) {
            return Results.success();
        } else {
            throw new ServiceException("短链接映射删除失败");
        }
    }

    @PutMapping("/api/shortlink-mappers/recover/{id}")
    Result<Void> recover(@PathVariable Long id) {
        shortLinkMapperService.recover(id);
        return Results.success();
    }

    @GetMapping("/api/shortlink-mappers/origin")
    Result<String> getOriginByShortLink(@RequestParam("domain") String domain, @RequestParam("shortUri") String shortUri) {
        String originUrl = shortLinkMapperService.getOriginByShortLink(new ShortLinkReqDTO(domain, shortUri));
        return Results.success(originUrl);
    }
}
